<template>
  <div class="share-access-container">
    <div class="share-access-card">

      <div v-if="loading" class="loading">
        <el-icon class="is-loading" :size="40"><Loading /></el-icon>
        <p>正在加载分享信息...</p>
      </div>

      <div v-else-if="!shareInfo" class="error">
        <el-icon :size="60" color="#f56c6c"><Warning /></el-icon>
        <h3>分享不存在或已过期</h3>
        <p>请检查分享链接是否正确</p>
        <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
      </div>

      <div v-else class="share-content">
        <!-- 分享信息展示 -->
        <div class="share-info">
          <div class="file-icon">
            <el-icon :size="60" :color="shareInfo.file.isFolder ? '#409eff' : '#67c23a'">
              <Folder v-if="shareInfo.file.isFolder" />
              <Document v-else />
            </el-icon>
          </div>

          <div class="file-details">
            <h3>{{ shareInfo.shareName }}</h3>
            <div class="file-meta">
              <p>文件名: {{ shareInfo.file.fileName }}</p>
              <p v-if="!shareInfo.file.isFolder">文件大小: {{ formatFileSize(shareInfo.file.fileSize) }}</p>
              <p>分享时间: {{ formatDateTime(shareInfo.file.createTime) }}</p>
              <p v-if="shareInfo.expireTime">
                过期时间: {{ formatDateTime(shareInfo.expireTime) }}
              </p>
              <p v-else>永久有效</p>
            </div>
          </div>
        </div>

        <!-- 密码验证 -->
        <div v-if="shareInfo.needPassword && !isVerified" class="password-section">
          <el-divider />
          <div class="password-form">
            <h4>请输入提取码</h4>
            <el-form @submit.prevent="handleVerifyPassword">
              <el-form-item>
                <el-input
                  v-model="password"
                  placeholder="请输入4位提取码"
                  maxlength="4"
                  style="width: 200px"
                  @keyup.enter="handleVerifyPassword"
                />
                <el-button
                  type="primary"
                  @click="handleVerifyPassword"
                  :loading="verifyLoading"
                  style="margin-left: 10px"
                >
                  确定
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 文件操作 -->
        <div v-if="!shareInfo.needPassword || isVerified" class="file-actions">
          <el-divider />
          <div class="action-buttons">
            <el-button
              v-if="shareInfo.permissions >= 2"
              type="primary"
              @click="handleDownload"
              :loading="downloadLoading"
              size="large"
            >
              <el-icon><Download /></el-icon>
              下载文件
            </el-button>
            <el-button
              v-if="canPreview"
              @click="handlePreview"
              size="large"
            >
              <el-icon><View /></el-icon>
              预览文件
            </el-button>
          </div>

          <div class="share-stats">
            <p>
              <el-icon><View /></el-icon>
              已有 {{ shareInfo.visitCount }} 人查看
            </p>
            <p v-if="shareInfo.permissions >= 2">
              <el-icon><Download /></el-icon>
              已有 {{ shareInfo.downloadCount }} 人下载
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <FilePreviewDialog v-model="showPreviewDialog" :file-info="previewFileInfo" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getShare, verifySharePassword, recordShareDownload } from '@/api/share'
import { generateDownloadUrl } from '@/api/file'
import FilePreviewDialog from '@/components/FilePreviewDialog.vue'
import {
  Loading,
  Warning,
  Folder,
  Document,
  Download,
  View
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const verifyLoading = ref(false)
const downloadLoading = ref(false)
const shareInfo = ref<any>(null)
const password = ref('')
const isVerified = ref(false)

// 预览相关
const showPreviewDialog = ref(false)
const previewFileInfo = ref<any>(null)

// 计算属性
const canPreview = computed(() => {
  if (!shareInfo.value?.file) return false
  const file = shareInfo.value.file
  const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
  const textTypes = ['txt', 'md', 'json', 'xml', 'csv']

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  return imageTypes.includes(ext) || textTypes.includes(ext)
})

// 工具方法
const formatFileSize = (size: number): string => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + ' MB'
  return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

const formatDateTime = (dateTime: string): string => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取分享信息
const fetchShareInfo = async () => {
  try {
    loading.value = true
    const shareCode = route.params.shareCode as string

    if (!shareCode) {
      shareInfo.value = null
      return
    }

    const result = await getShare(shareCode)
    shareInfo.value = result

    // 如果不需要密码，直接标记为已验证
    if (!result.needPassword) {
      isVerified.value = true
    }
  } catch (error: any) {
    console.error('获取分享信息失败:', error)
    shareInfo.value = null
    ElMessage.error(error.message || '获取分享信息失败')
  } finally {
    loading.value = false
  }
}

// 验证密码
const handleVerifyPassword = async () => {
  if (!password.value || password.value.length !== 4) {
    ElMessage.error('请输入4位提取码')
    return
  }

  try {
    verifyLoading.value = true
    const shareCode = route.params.shareCode as string

    await verifySharePassword(shareCode, password.value)
    isVerified.value = true
    ElMessage.success('验证成功')
  } catch (error: any) {
    ElMessage.error(error.message || '提取码错误')
  } finally {
    verifyLoading.value = false
  }
}

// 下载文件
const handleDownload = async () => {
  if (!shareInfo.value?.file) return

  try {
    downloadLoading.value = true

    // 生成下载链接
    const downloadInfo = await generateDownloadUrl(shareInfo.value.file.id)

    // 记录下载统计
    const shareCode = route.params.shareCode as string
    await recordShareDownload(shareCode)

    // 创建下载链接
    const link = document.createElement('a')
    link.href = downloadInfo.downloadUrl
    link.download = shareInfo.value.file.fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('开始下载')

    // 更新下载次数
    shareInfo.value.downloadCount++
  } catch (error: any) {
    ElMessage.error(error.message || '下载失败')
  } finally {
    downloadLoading.value = false
  }
}

// 预览文件
const handlePreview = () => {
  if (shareInfo.value?.file) {
    previewFileInfo.value = shareInfo.value.file
    showPreviewDialog.value = true
  }
}

// 初始化
onMounted(() => {
  fetchShareInfo()
})
</script>

<style scoped>
.share-access-container {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.share-access-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  width: 100%;
  overflow: hidden;
}

.card-header {
  background: #409eff;
  color: white;
  padding: 20px;
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
}

.loading, .error {
  text-align: center;
  padding: 60px 20px;
}

.loading p, .error p {
  margin-top: 20px;
  color: #666;
}

.error h3 {
  margin: 20px 0 10px 0;
  color: #f56c6c;
}

.share-content {
  padding: 30px;
}

.share-info {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 20px;
}

.file-icon {
  flex-shrink: 0;
}

.file-details {
  flex: 1;
}

.file-details h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 20px;
}

.file-meta p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}

.password-section {
  text-align: center;
  padding: 20px 0;
}

.password-form h4 {
  margin-bottom: 20px;
  color: #333;
}

.file-actions {
  text-align: center;
}

.action-buttons {
  margin: 30px 0;
  display: flex;
  justify-content: center;
  gap: 15px;
  flex-wrap: wrap;
}

.share-stats {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.share-stats p {
  display: flex;
  align-items: center;
  gap: 5px;
  margin: 0;
  color: #666;
  font-size: 14px;
}

@media (max-width: 768px) {
  .share-access-container {
    padding: 10px;
  }

  .share-info {
    flex-direction: column;
    text-align: center;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .share-stats {
    flex-direction: column;
    gap: 10px;
  }
}
</style>